package com.xxj.duck.ui;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.xxj.duck.R;

public class GameScore {

	private static final int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT;

	private final String GAME_NAME = "DUCK_GAME_";
	private final String SP_PREFS_NAME = GAME_NAME + "GAME_SCORE6";
	private final String RANK_NAME = GAME_NAME + "gameName";
	private final String RANK_SCORE = GAME_NAME + "gameScore";
	private final String YOUR_RANK = GAME_NAME + "yourRanking";

	private SharedPreferences scoreSP;
	private Activity gameActivity;

	private ProgressDialog pgDialog = null;
	private final int update_score_OK = 1;
	private final int update_score_Failed_Err = 2;
	private final int update_score_Failed_Network = 3;

	public GameScore(Activity gameActivity) {
		this.gameActivity = gameActivity;
		scoreSP = gameActivity.getSharedPreferences(SP_PREFS_NAME, 0);
		initGameParamWithServer();
	}

	private void initGameParamWithServer() {
		this.updateScores(false);
		this.updatePlayCount();
	}

	private void updatePlayCount() {
		new Thread() {
			@Override
			public void run() {
				JSONObject myScore = null;
				try {
					myScore = HttpUtil.getGameScore(GAME_NAME, getDevID());
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(myScore == null){
					submit(0.0);
				} else {
					HttpUtil.updatePlayCount(GAME_NAME, getDevID());
				}
			}
		}.start();
	}

	public void updateScores(final boolean showPgDialog) {
		if (showPgDialog) {
			this.showPgDialog(R.string.upate_title, R.string.update_message);
		}
		new Thread("update score") {
			@Override
			public void run() {
				Message message = new Message();
				String s = "";
				try {
					s = HttpUtil.getScoresTOP3();
				} catch (Exception e) {
					e.printStackTrace();
					message.what = update_score_Failed_Network;
				}
				if (s != null && !"".equals(s)) {
					try {
						JSONArray jsonArray = new JSONObject(s)
								.getJSONArray("resultList");
						SharedPreferences.Editor editor = scoreSP.edit();
						editor.clear();
						for (int i = 0; i < jsonArray.length(); i++) {
							if (i > 2) {
								break;
							}
							JSONObject jsonObj = (JSONObject) jsonArray.opt(i);
							editor.putString(RANK_NAME + (i + 1),
									jsonObj.getString("userName"));
							editor.putInt(RANK_SCORE + (i + 1),
									jsonObj.getInt("gameScore"));
						}
						editor.putString(YOUR_RANK, getYourScoreRank());
						editor.commit();
						message.what = update_score_OK;
					} catch (Exception e) {
						e.printStackTrace();
						message.what = update_score_Failed_Err;
					}
				}
				if (showPgDialog) {
					handler.sendMessage(message);
				}
			}
		}.start();
	}

	public boolean submitScore(final Double score) {
		String userName = getUserName();
		if (userName == null || "".equals(userName.trim())) {
			Toast.makeText(gameActivity.getApplicationContext(),
					"must input name!", Toast.LENGTH_SHORT).show();
			return false;
		}

		this.showPgDialog(R.string.submit_title, R.string.submit_message);
		// save in local

		// save in server
		new Thread("submit score") {
			@Override
			public void run() {
				Message message = submit(score);
				message.what = update_score_OK;
				handler.sendMessage(message);
			}
		}.start();
		
		this.updateScores(false);
		return true;
	}
	
	private Message submit(final Double score) {
		Message message = new Message();
		TelephonyManager tm = (TelephonyManager) gameActivity
				.getSystemService(Context.TELEPHONY_SERVICE);
		String deviceId = tm.getDeviceId();
		String deviceSoftVersion = android.os.Build.VERSION.RELEASE
				+ "_" + android.os.Build.BRAND + "_"
				+ android.os.Build.DEVICE;
		String phoneNumber = tm.getLine1Number();
		if (phoneNumber == null || "".equals(phoneNumber)) {
			phoneNumber = "10086";
		}
		try {
			HttpUtil.submitScore(GAME_NAME, Double.valueOf(score)
					.intValue(), getUserName(), deviceId,
					deviceSoftVersion, phoneNumber);
		} catch (Exception ex) {

		}
		return message;
	}
	
	private String getYourScoreRank() throws Exception {
		return HttpUtil.queryMyRanking(GAME_NAME, getDevID());
	}

	private void showPgDialog(int tilte, int message) {
		pgDialog = new ProgressDialog(gameActivity);
		pgDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pgDialog.setTitle(gameActivity.getResources().getString(tilte));
		pgDialog.setMessage(gameActivity.getResources().getString(message));
		pgDialog.show();
	}

	public void showScoreUI() {
		gameActivity.runOnUiThread(new Thread() {
			public void run() {
				if (gameActivity.findViewById(R.id.settingsDialog)
						.getVisibility() == View.GONE
						&& gameActivity.findViewById(R.id.backMenuDialog)
								.getVisibility() == View.GONE) {
					initGameScoreRankUI();
					gameActivity.findViewById(R.id.scoreRankDialog).setVisibility(
							View.VISIBLE);
				}
			}

		});
	}

	private void initGameScoreRankUI() {
		TableLayout tableLayout = (TableLayout) gameActivity
				.findViewById(R.id.scoreRankTableLayout);
		tableLayout.removeAllViews();
		String space = "        ";
		for (int i = 1; i <= 3; i++) {

			TextView tvNO = new TextView(gameActivity);
			tvNO.setText(space + i + ".");

			TextView tvName = new TextView(gameActivity);
			tvName.setText(space + this.getRankName(i) + space);

			TextView tvScore = new TextView(gameActivity);
			tvScore.setText(space + this.getRankScore(i) + space);

			TableRow tableRow = new TableRow(gameActivity);
			tableRow.addView(tvNO);
			tableRow.addView(tvName);
			tableRow.addView(tvScore);

			tableLayout.addView(tableRow, new TableLayout.LayoutParams(
					WRAP_CONTENT, WRAP_CONTENT));
		}
		TextView yourScoreRank = (TextView) gameActivity
				.findViewById(R.id.yourScoreRank);
		int[] rankings = getMyScoreInt(scoreSP.getString(YOUR_RANK, " 100 / 4"));
		String ranking = String.format(
				gameActivity.getResources().getString(
						R.string.your_score_ranking), rankings[0], rankings[1]);
		yourScoreRank.setText(ranking);
	}

	private int[] getMyScoreInt(String ranking) {
		System.out.println("input args: " + ranking);
		if(ranking.startsWith("\"")){
			ranking = ranking.substring(1);
		}
		if(ranking.endsWith("\"")){
			ranking = ranking.substring(0,ranking.length()-1);
		}
		System.out.println("output args: " + ranking);
		int[] rs = new int[2];
		String[] vals = ranking.split("/");
		
		String score = vals[0].trim();
		if(score == null && "".equals(score)){
			score = "100";
		}
		rs[0] = Integer.valueOf(score);
		
		String rank = vals[1].trim();
		if(rank == null && "".equals(rank)){
			rank = "4";
		}
		rs[1] = Integer.valueOf(rank);
		return rs;
	}

	private String getRankName(int rank) {
		return scoreSP.getString(RANK_NAME + rank, "user_" + rank);
	}

	private int getRankScore(int rank) {
		return scoreSP.getInt(RANK_SCORE + rank, 0);
	}

	public void showSubmitSocreUI(Double score) {
		LinearLayout scoresLayout = (LinearLayout) gameActivity
				.findViewById(R.id.saveScoreDialog);
		scoresLayout.setVisibility(View.VISIBLE);
		TextView scoreTextCtrl = (TextView) scoresLayout
				.findViewById(R.id.scoreText);
		scoreTextCtrl.setText(gameActivity.getResources().getString(
				R.string.wish_to_save_scores)
				+ " (" + score.intValue() + ")");
	}

	private String getUserName() {
		LinearLayout scoresLayout = (LinearLayout) gameActivity
				.findViewById(R.id.saveScoreDialog);
		TextView userNameTV = (TextView) scoresLayout
				.findViewById(R.id.userName);
		return userNameTV.getText().toString();
	}

	

	private String getDevID() {
		TelephonyManager tm = (TelephonyManager) gameActivity
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getDeviceId();
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			String tip = "";
			switch (msg.what) {
			case update_score_OK:
				// update rank view.
				initGameScoreRankUI();
				if (pgDialog != null) {
					pgDialog.dismiss();
				}
				tip = gameActivity.getResources().getString(R.string.update_ok);
				break;
			case update_score_Failed_Network:
				if (pgDialog != null) {
					pgDialog.dismiss();
				}
				tip = gameActivity.getResources().getString(
						R.string.update_failed_network);
				break;
			case update_score_Failed_Err:
				if (pgDialog != null) {
					pgDialog.dismiss();
				}
				tip = gameActivity.getResources().getString(
						R.string.update_failed_error);
				break;
			default:
				break;
			}
			Toast.makeText(gameActivity.getApplicationContext(), tip,
					Toast.LENGTH_SHORT).show();
		}
	};

	public String getHighGameScore() {
		return "" + getRankScore(1);
	}
}
